import { UIActionUtil } from '@ibiz-template/runtime';
import { IDEFormButton } from '@ibiz/model-core';
import { EditFormController } from '../../edit-form';
import { FormDetailController } from '../form-detail';
import { FormButtonState } from './form-button.state';

/**
 * 表单按钮控制器
 *
 * @author lxm
 * @date 2022-09-04 15:09:52
 * @export
 * @class FormButtonController
 * @extends {FormDetailController}
 */
export class FormButtonController extends FormDetailController<IDEFormButton> {
  declare state: FormButtonState;

  protected createState(): FormButtonState {
    return new FormButtonState(this.parent?.state);
  }

  /**
   * 表单数据
   *
   * @author lxm
   * @date 2022-09-01 22:09:48
   * @readonly
   */
  get data(): IData {
    return this.form.data;
  }

  /**
   * 按钮点击处理回调
   *
   * @author lxm
   * @date 2022-09-28 21:09:33
   * @param {MouseEvent} event
   */
  async onClick(event: MouseEvent): Promise<void> {
    this.state.loading = true;
    try {
      if (this.model.actionType === 'UIACTION') {
        await this.doUIAction(event);
      }
      await this.doFormItemUpdate();
    } finally {
      this.state.loading = false;
    }
  }

  /**
   * 执行界面行为
   *
   * @author lxm
   * @date 2022-10-19 22:10:20
   * @param {MouseEvent} event
   * @returns {*}  {Promise<void>}
   */
  async doUIAction(event: MouseEvent): Promise<void> {
    const actionId = this.model.uiactionId;
    await UIActionUtil.execAndResolved(actionId!, {
      context: this.form.context,
      params: this.form.params,
      data: [this.data],
      view: this.form.view,
      event,
      noWaitRoute: true,
    });
  }

  /**
   * 执行表单项更新
   *
   * @author lxm
   * @date 2022-10-19 22:10:22
   * @returns {*}  {Promise<void>}
   */
  async doFormItemUpdate(): Promise<void> {
    if (!this.model.deformItemUpdateId) {
      return;
    }
    await (this.form as EditFormController).updateFormItem(
      this.model.deformItemUpdateId,
    );
  }
}
